package com.tianlang.security;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.tianlang.domain.pojo.Account;
import com.tianlang.service.IUserManager;
import com.tianlang.util.StringUtil;

/**
 * 该类的主要作用是为Spring Security提供一个经过用户认证后的UserDetails。
 * 该UserDetails包括用户名、密码、是否可用、是否过期等信息。
 * 
 * @author mchp 自定义授权用户信息处理 用户拥有的权限
 *
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

	private static Logger LOG = Logger.getLogger(UserDetailsServiceImpl.class);

	@Autowired
	private IUserManager userManager;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		if (StringUtil.isEmpty(username)) {
			LOG.error("用户名为空");
			// throw new UsernameNotFoundException("用户名不能为空!");
			return null;
		}
		Account _account = userManager.getAccountByName(username);
		if (_account == null) {
			// throw new UsernameNotFoundException("用户名不存在!");
			return null;
		}
		User user = new User(_account.getUsername(), _account.getPassword(), _account.getAuthorities());
		return user;
	}

}
